package com.qk.management.web.filter;


import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 *
 * @author MrZhao
 * @created 2025-10-11 10:58
 * @description 登录校验过滤器
 *
 */
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        // 1 将请求对象和响应对象强转为HttpServletRequest 和 HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 2. 获取请求的路径。  比如 /login /users
        String path = request.getRequestURI();
        log.info("-----拦截到请求路径是：{}-----", path);
        // 3. 判断当前请求是否为登录请求 /login
        boolean isLoginReq = ObjectUtil.equals(LOGIN_PATH, path);
        if (isLoginReq) {
            chain.doFilter(request, response);
            return;
        }
        // 4. 不是登录请求获取请求头中名字叫 token 的请求头
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtil.isEmpty(token)) {
            response.setStatus(401);
            return;
        }
        // 5. 验证token
        try {
            Claims claims = JwtUtil.parseToken(token);
            // 获取用户信息 TODO 如何处理？
            String username = claims.get("username", String.class);
            log.info("-----用户信息是：{}-----", username);
            Object id = claims.get("id");
            log.info("-----用户id是：{}-----", id);
            // 放行
            chain.doFilter(request, response);
            return;
        } catch (Exception e) {
            log.error("-----token验证失败-----", e);
            response.setStatus(401);
            return;
        }
    }
}
